package com.cma.common.web.interceptor;

import com.cma.common.os.OsInfoUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.util.Date;

/**
 * Created by wangbing on 14-4-17.
 */
public class StaticVersionInterceptor implements HandlerInterceptor {
    private static final Log logger = LogFactory.getLog(StaticVersionInterceptor.class);


    private static final Date NOW = new Date();
    private String yyyyMMddhhmmss = DateFormatUtils.format(NOW, "yyyyMMddhhmmss");

    private boolean isDev = OsInfoUtil.isMacOS() || OsInfoUtil.isMacOSX() || OsInfoUtil.isWindows();


    @Value("${site.name}")
    private String siteName;

    @Value("${site.sys_name}")
    private String siteSysName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getServletPath();
        String fullUrl = request.getRequestURL().toString();

        if (url.startsWith("/statics/")) {
            return true;
        }

        if (url.startsWith("/favicon.png")) {
            return true;
        }


        if (url.endsWith(".html")) {
            request.setAttribute("dc", "20161227");

            if (isDev) {
                request.setAttribute("staticVersion", System.currentTimeMillis());
            } else {
                request.setAttribute("staticVersion", yyyyMMddhhmmss);
            }


            InetAddress addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress().toString();
            String address = addr.getHostName().toString();

            request.setAttribute("site_host_ip", ip);
            request.setAttribute("site_host_name", address);

            request.setAttribute("site_sys_name", siteSysName);
            request.setAttribute("sys_title", siteSysName);

            request.setAttribute("site_name", siteName);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
